const router = require('koa-router')();
const db = require('../dbs/voiceAccountBook');
const userDB = require('../dbs/user');
const log = require('../libs/log4js')('ACCOUNTRouter');
const utils = require('../libs/utils');
const worker = require('worker_threads');
const md5 = require('md5-node');
const fun = require('../functions/charData');
const fs = require('fs');
const path = require('path');

router.post('/add', async (ctx) => {
  const body = ctx.request.body;
  const key = ['year', 'month', 'date', 'money', 'payType', 'consumptionType'];
  if (!utils.valideData(key, body)) {
    if (!body.desc) body.desc = '';
    let user = body.__userId;
    delete body.__userId;
    body.user = user;
    body.id = md5(new Date().getTime().toString(16));
    try {
      const report = await db.insert({
        data: body
      });
      ctx.body = JSON.stringify({
        code: 200,
        data: report.toString,
        msg: '成功',
      });
    } catch (e) {
      log.debug('新加报错', e);
      ctx.body = JSON.stringify({
        code: 100,
        data: '',
        msg: '添加报错',
      });
    }
  } else {
    ctx.body = JSON.stringify({
      code: 101,
      data: '',
      msg: '参数有误',
    });
  }
});

router.get('/getList', async (ctx) => {
  const user = ctx.request.body.__userId;
  console.log('user', user);
  try {
    const report = await db.query({
      queryData: {
        user: user
      },
      options: {
        _id: 0,
        __v: 0,
        updateDate: 0,
        createDate: 0,
        user: 0
      },
      sort: {
        dateTime: -1
      }
    });
    ctx.body = JSON.stringify({
      code: 200,
      data: report,
      msg: 'suc'
    });
  } catch (e) {
    log.debug('查询有误', e);
    ctx.body = JSON.stringify({
      code: 100,
      data: '',
      msg: '查询报错',
    });
  }
});
/*
* 列表添加
* */
router.post('/addList', async (ctx) => {
  const body = ctx.request.body;
  const key = ['year', 'month', 'date', 'money', 'payType', 'consumptionType'];
  const data = body.data;
  let flag;
  const length = data.length;
  const now = new Date().getTime();
  for (let i = 0; i < length; i++) {
    let v = data[i];
    flag = utils.valideData(key, v);
    if (flag) {
      break;
    } else {
      if (!v.desc) v.desc = '';
      v.id = md5((now + i).toString(16));
      v.createDate = v.updateDate = now.toString();
      v.user = body.__userId;
    }
  }
  if (!flag) {
    try {
      const report = await db.insetArray(data);
      ctx.body = JSON.stringify({
        code: 200,
        data: report.toString,
        msg: '成功',
      });
    } catch (e) {
      log.debug('新加报错', e);
      ctx.body = JSON.stringify({
        code: 100,
        data: '',
        msg: '添加报错',
      });
    }
  } else {
    ctx.body = JSON.stringify({
      code: 101,
      data: '',
      msg: '参数有误',
    });
  }
});

/*语音转文字*/
function vtt(files) {
  return new Promise((s) => {
    const th = new worker.Worker(path.resolve(__dirname, './voiceToText.js'), {
      workerData: {
        file: files,
      }
    });
    th.once('message', data => {
      console.log('aaa', data);
      s(data[0].result);
    });
  });
}

router.post('/voiceToText', async (ctx) => {
  const files = ctx.request.files;
  console.log(files.path);
  const str = await vtt(files.voice.path);
  console.log(str);
  if (str) {
    ctx.body = JSON.stringify({
      code: 200,
      data: str,
      msg: 'suc'
    });
  } else {
    ctx.body = JSON.stringify({
      code: 100,
      msg: '转义失败, 请重新说'
    });
  }
});

/*
* 返回年月日数据
* */
router.post('/allData', async (ctx) => {
  const dateObj = new Date();
  let user = ctx.request.body.__userId;
  let obj = {};
  obj.year = await fun.chartYearMonthDayData(user, '2', {
    year: dateObj.getFullYear()
  });
  obj.month = await fun.chartYearMonthDayData(user, '1', {
    year: dateObj.getFullYear(),
    month: dateObj.getMonth() + 1
  });
  obj.week = await fun.chartYearMonthDayData(user, '0', {});
  ctx.body = JSON.stringify({
    code: 200,
    msg: 'suc',
    data: obj
  });
});

/*柱形图数据*/
router.post('/barData', async (ctx) => {
  try {
    const body = ctx.request.body;
    let data;
    switch (body.type) {
      case 'week':
        data = await fun.chartWeekData(body.__userId);
        break;
      case 'month':
        data = await fun.chartMonthData(body.__userId);
        break;
      case 'year':
        data = await fun.chartYearData(body.__userId);
        break;
      default:
        break;
    }
    ctx.body = JSON.stringify({
      code: 200,
      msg: 'suc',
      data
    });
  } catch (e) {
    log.error(e);
    ctx.body = JSON.stringify({
      code: 100,
      msg: '服务器错误'
    });
  }
});

router.post('/pieData', async (ctx) => {
  try {
    const body = ctx.request.body;
    let data = {};
    let dataObj;
    if (body.type === '0') {
      dataObj = {
        date: body.date
      };
    } else {
      dataObj = {
        year: body.year,
        month: body.month
      };
    }
    data.pay = await fun.pieData(body.__userId, body.type, 'payType', dataObj);
    data.consumption = await fun.pieData(body.__userId, body.type, 'consumptionType', dataObj);
    ctx.body = JSON.stringify({
      code: 200,
      msg: 'suc',
      data
    });
  } catch (e) {
    log.error(e);
    ctx.body = JSON.stringify({
      code: 100,
      msg: '服务器错误'
    });
  }
});

router.post('/search', async (ctx) => {
  const body = ctx.request.body;
  body.pageSize = body.pageSize || 10;
  body.pageNo = body.pageNo || 1;
  const query = {};
  query.user = body.__userId;
  if (body.model === 'date') {
    query.date = body.date;
  } else {
    query.year = body.year;
    query.month = body.month;
  }
  if (body.pay) {
    query.payType = body.pay;
  }
  if (body.consumption) {
    query.consumptionType = body.consumption;
  }
  if (body.maxOrMin && body.maxOrMinValue) {
    /*(>=) 大于等于 - $gte
(<= ) 小于等于 - $lte*/
    if (body.maxOrMin === 1) { // 大于等于
      query.money = {
        $gte: body.maxOrMinValue
      };
    } else { // 小于等于
      query.money = {
        $lte: body.maxOrMinValue
      };
    }
  }
  const allCount = await db.computedCount(query);
  const data = await db.search({
    queryData: query,
    options: {
      _id: 0,
      __v: 0,
      updateDate: 0,
      createDate: 0,
      user: 0
    },
    sort: {
      dateTime: -1
    },
    skip: body.pageSize * (body.pageNo - 1),
    limit: body.pageSize
  });
  ctx.body = JSON.stringify({
    code: 200,
    data: {
      data,
      allCount,
      pageNo: body.pageNo,
      pageSize: body.pageSize
    }
  });
});

router.post('/log', async (ctx) => {
  const body = ctx.request.body;
  log.debug(body.__userId);
  let user = await userDB.getUserById(body.__userId);
  log.debug(user);
  user = user && user[0];
  if (!user || user.userName !== 'Cander') {
    log.info('越权查询日志, 查询用户 => ' + user && user.name);
    ctx.body = JSON.stringify({
      code: 1200,
      msg: '无权限查看'
    });
    return;
  }
  const fileName = `${body.type}.${body.date}.log`;
  const filePath = path.resolve(__dirname, '../libs/log/' + fileName);
  log.debug(filePath);
  const fileHave = fs.existsSync(filePath);
  console.log(fileHave);
  if (!fileHave) {
    log.debug('没有找到日志文件', filePath);
    ctx.body = JSON.stringify({
      code: 1201,
      msg: '没有找到该文件'
    });
  } else {
    try {
      const data = fs.readFileSync(filePath, 'utf-8');
      ctx.body = JSON.stringify({
        code: 200,
        data,
        msg: ''
      });
    } catch (e) {
      log.error('读取日志文件错误');
      log.error(e);
      ctx.body = JSON.stringify({
        code: 1202,
        msg: '读取文件错误'
      });
    }
  }
});

module.exports = router;
